package com.yc.web.servlets;

import com.yc.web.OrderBiz;
import com.yc.web.model.JsonModel;
import com.yc.bean.ShoeOrder;
import com.yc.bean.User;
import com.yc.web.model.CartItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import static com.yc.utils.YcConstants.USER;


@WebServlet(name = "CustServlet",value = "/custOp.action")
public class CustServlet extends BaseServlet{

    protected void confirmOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JsonModel jm = new JsonModel();

        //取参数    订单中的参数   ，   购物车
        ShoeOrder order = null;
        try {
            order = super.parseObjectFromRequest(req, ShoeOrder.class);
            //调用业务层处理
            HttpSession session = req.getSession();//取出session会话对象
            Map<Integer, CartItem> cart = (Map<Integer, CartItem>) session.getAttribute("cart");
            Set<CartItem> cartItems = new HashSet<>(cart.values()) ;

            User user = (User) session.getAttribute(USER);
            OrderBiz ob = new OrderBiz();
            int result =  ob.order(order,cartItems,user);

            jm.setCode(1);
            //成功后    删除session中的购物车缓存
            session.removeAttribute("cart");

        } catch (Exception e) {
            e.printStackTrace();
            jm.setCode(0);
            jm.setError(e.getMessage());
        }

        super.writeJson(jm,resp);
    }
}
